import java.util.*;

// --------------------- 基础数据结构 ---------------------
class Position {
    private double x;
    private double y;

    public Position(double x, double y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public String toString() {
        return String.format("(%.2f, %.2f)", x, y);
    }

    // Getter & Setter
    public double getX() { return x; }
    public double getY() { return y; }
}

class SoilData {
    private double humidity;
    private double ph;
    private double nutrientLevel;

    public SoilData(double humidity, double ph, double nutrientLevel) {
        this.humidity = humidity;
        this.ph = ph;
        this.nutrientLevel = nutrientLevel;
    }

    @Override
    public String toString() {
        return String.format("湿度=%.2f%%, pH=%.1f, 养分含量=%.2f", humidity, ph, nutrientLevel);
    }

    // Getter & Setter
    public double getHumidity() { return humidity; }
    public double getPh() { return ph; }
    public double getNutrientLevel() { return nutrientLevel; }
}

class CropStatus {
    private String growthStage;
    private double healthIndex;

    public CropStatus(String growthStage, double healthIndex) {
        this.growthStage = growthStage;
        this.healthIndex = healthIndex;
    }

    @Override
    public String toString() {
        return String.format("生长阶段=%s, 健康指数=%.2f", growthStage, healthIndex);
    }

    // Getter & Setter
    public String getGrowthStage() { return growthStage; }
    public double getHealthIndex() { return healthIndex; }
}

class WeatherData {
    private double temperature;
    private double humidity;
    private double windSpeed;

    public WeatherData(double temperature, double humidity, double windSpeed) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.windSpeed = windSpeed;
    }

    @Override
    public String toString() {
        return String.format("温度=%.1f℃, 湿度=%.2f%%, 风速=%.2f m/s",
                temperature, humidity, windSpeed);
    }

    // Getter & Setter
    public double getTemperature() { return temperature; }
    public double getHumidity() { return humidity; }
    public double getWindSpeed() { return windSpeed; }
}

// --------------------- 设计模式实现 ---------------------
// 1. 工厂方法模式：创建农机设备
interface FarmMachineFactory {
    FarmMachine createMachine(String type);
}

class ConcreteFarmMachineFactory implements FarmMachineFactory {
    @Override
    public FarmMachine createMachine(String type) {
        switch (type.toLowerCase()) {
            case "播种机": return new Seeder();
            case "喷药机": return new Sprayer();
            case "收割机": return new Harvester();
            default: throw new IllegalArgumentException("未知农机类型: " + type);
        }
    }
}

// 2. 策略模式：路径规划算法
interface PathPlanningStrategy {
    List<Position> calculatePath(Map<Position, SoilData> soilData, List<Position> obstacles);
}

class WetSoilPathStrategy implements PathPlanningStrategy {
    @Override
    public List<Position> calculatePath(Map<Position, SoilData> soilData, List<Position> obstacles) {
        System.out.println("[湿地区域路径规划] 避开湿度>80%的区域");
        List<Position> path = new ArrayList<>();

        // 简单模拟路径计算
        path.add(new Position(0, 0));
        path.add(new Position(50, 50));
        path.add(new Position(100, 100));

        return path;
    }
}

class NormalPathStrategy implements PathPlanningStrategy {
    @Override
    public List<Position> calculatePath(Map<Position, SoilData> soilData, List<Position> obstacles) {
        System.out.println("[常规路径规划] 优先选择最短路径");
        List<Position> path = new ArrayList<>();

        // 简单模拟路径计算
        path.add(new Position(0, 0));
        path.add(new Position(100, 100));

        return path;
    }
}

// 3. 观察者模式：环境数据更新
interface EnvironmentObserver {
    void update(SoilData soilData, CropStatus cropStatus, WeatherData weatherData);
}

class EnvironmentMonitor {
    private List<EnvironmentObserver> observers = new ArrayList<>();
    private SoilData currentSoilData;
    private CropStatus currentCropStatus;
    private WeatherData currentWeatherData;

    public void addObserver(EnvironmentObserver observer) {
        observers.add(observer);
    }

    public void removeObserver(EnvironmentObserver observer) {
        observers.remove(observer);
    }

    public void updateEnvironmentData(SoilData soilData, CropStatus cropStatus, WeatherData weatherData) {
        this.currentSoilData = soilData;
        this.currentCropStatus = cropStatus;
        this.currentWeatherData = weatherData;
        notifyObservers();
    }

    private void notifyObservers() {
        for (EnvironmentObserver observer : observers) {
            observer.update(currentSoilData, currentCropStatus, currentWeatherData);
        }
    }
}

// 4. 状态模式：农机状态管理
interface MachineState {
    void handle(FarmMachine context);
}

class WorkingState implements MachineState {
    @Override
    public void handle(FarmMachine context) {
        System.out.printf("[%s] 正在作业中...\n", context.getType());
        // 模拟作业逻辑...
    }
}

class IdleState implements MachineState {
    @Override
    public void handle(FarmMachine context) {
        System.out.printf("[%s] 待机状态，等待任务分配\n", context.getType());
    }
}

class FaultState implements MachineState {
    @Override
    public void handle(FarmMachine context) {
        System.out.printf("[%s] 故障状态，需要维修\n", context.getType());
    }
}

// 5. 责任链模式：安全事件处理
abstract class SafetyHandler {
    protected SafetyHandler nextHandler;

    public SafetyHandler setNext(SafetyHandler handler) {
        this.nextHandler = handler;
        return handler;
    }

    public abstract void handleEvent(SafetyEvent event);
}

class ObstacleHandler extends SafetyHandler {
    @Override
    public void handleEvent(SafetyEvent event) {
        if (event.getType() == SafetyEvent.Type.OBSTACLE) {
            System.out.printf("[障碍物处理] 检测到障碍物: %s\n", event.getDescription());
            // 模拟避障逻辑...
            event.setResolved(true);
        } else if (nextHandler != null) {
            nextHandler.handleEvent(event);
        }
    }
}

class WeatherHandler extends SafetyHandler {
    @Override
    public void handleEvent(SafetyEvent event) {
        if (event.getType() == SafetyEvent.Type.WEATHER) {
            System.out.printf("[天气处理] 恶劣天气: %s\n", event.getDescription());
            // 模拟天气应对逻辑...
            event.setResolved(true);
        } else if (nextHandler != null) {
            nextHandler.handleEvent(event);
        }
    }
}

class FaultHandler extends SafetyHandler {
    @Override
    public void handleEvent(SafetyEvent event) {
        if (event.getType() == SafetyEvent.Type.FAULT) {
            System.out.printf("[故障处理] 设备故障: %s\n", event.getDescription());
            // 模拟故障处理逻辑...
            event.setResolved(true);
        } else if (nextHandler != null) {
            nextHandler.handleEvent(event);
        }
    }
}

// 6. 命令模式：农机操作指令
interface Command {
    void execute();
}

class StartWorkCommand implements Command {
    private FarmMachine machine;

    public StartWorkCommand(FarmMachine machine) {
        this.machine = machine;
    }

    @Override
    public void execute() {
        System.out.printf("执行命令: 启动 [%s] 作业\n", machine.getType());
        machine.startWork();
    }
}

class StopWorkCommand implements Command {
    private FarmMachine machine;

    public StopWorkCommand(FarmMachine machine) {
        this.machine = machine;
    }

    @Override
    public void execute() {
        System.out.printf("执行命令: 停止 [%s] 作业\n", machine.getType());
        machine.stopWork();
    }
}

class CommandInvoker {
    private Command command;

    public void setCommand(Command command) {
        this.command = command;
    }

    public void executeCommand() {
        if (command != null) {
            command.execute();
        }
    }
}

// 7. 外观模式：系统简化接口
class FarmSystemFacade {
    private final FarmMachineManager machineManager;
    private final EnvironmentMonitor environmentMonitor;
    private final PathPlanner pathPlanner;
    private final SafetyHandler safetyChain;
    private final CommandInvoker commandInvoker;

    public FarmSystemFacade() {
        this.environmentMonitor = new EnvironmentMonitor();
        this.machineManager = new FarmMachineManager(environmentMonitor);
        this.pathPlanner = new PathPlanner();
        this.commandInvoker = new CommandInvoker();

        // 构建责任链
        this.safetyChain = new ObstacleHandler();
        safetyChain.setNext(new WeatherHandler()).setNext(new FaultHandler());
    }

    // 设备管理
    public void addMachine(String type) {
        machineManager.addMachine(type);
    }

    public void removeMachine(String id) {
        machineManager.removeMachine(id);
    }

    public void listMachines() {
        machineManager.listMachines();
    }

    // 环境监测
    public void updateEnvironmentData(SoilData soilData, CropStatus cropStatus, WeatherData weatherData) {
        environmentMonitor.updateEnvironmentData(soilData, cropStatus, weatherData);
    }

    // 路径规划
    public void planPath(String machineId, Map<Position, SoilData> soilData, List<Position> obstacles) {
        pathPlanner.planPath(machineId, soilData, obstacles);
    }

    // 安全事件处理
    public void handleSafetyEvent(SafetyEvent event) {
        safetyChain.handleEvent(event);
    }

    // 命令执行
    public void executeCommand(Command command) {
        commandInvoker.setCommand(command);
        commandInvoker.executeCommand();
    }

    public FarmMachine getMachine(String id) {
        return machineManager.getMachine(id);
    }
}

// 8. 代理模式：权限控制
class FarmMachineProxy implements FarmMachine {
    private final FarmMachine realMachine;
    private final User currentUser;

    public FarmMachineProxy(FarmMachine realMachine, User currentUser) {
        this.realMachine = realMachine;
        this.currentUser = currentUser;
    }

    @Override
    public String getId() {
        return realMachine.getId();
    }

    @Override
    public String getType() {
        return realMachine.getType();
    }

    @Override
    public double getFuelLevel() {
        return realMachine.getFuelLevel();
    }

    @Override
    public Position getPosition() {
        return realMachine.getPosition();
    }

    @Override
    public MachineState getState() {
        return realMachine.getState();
    }

    @Override
    public void startWork() {
        if (currentUser.hasPermission("START_WORK")) {
            realMachine.startWork();
        } else {
            System.out.println("权限不足: 无法启动设备");
        }
    }

    @Override
    public void stopWork() {
        if (currentUser.hasPermission("STOP_WORK")) {
            realMachine.stopWork();
        } else {
            System.out.println("权限不足: 无法停止设备");
        }
    }

    @Override
    public void update(SoilData soilData, CropStatus cropStatus, WeatherData weatherData) {
        realMachine.update(soilData, cropStatus, weatherData);
    }
}

// 9. 装饰器模式：动态添加功能
abstract class FarmMachineDecorator implements FarmMachine {
    protected final FarmMachine decoratedMachine;

    public FarmMachineDecorator(FarmMachine decoratedMachine) {
        this.decoratedMachine = decoratedMachine;
    }

    @Override
    public String getId() {
        return decoratedMachine.getId();
    }

    @Override
    public String getType() {
        return decoratedMachine.getType();
    }

    @Override
    public double getFuelLevel() {
        return decoratedMachine.getFuelLevel();
    }

    @Override
    public Position getPosition() {
        return decoratedMachine.getPosition();
    }

    @Override
    public MachineState getState() {
        return decoratedMachine.getState();
    }

    @Override
    public void startWork() {
        decoratedMachine.startWork();
    }

    @Override
    public void stopWork() {
        decoratedMachine.stopWork();
    }

    @Override
    public void update(SoilData soilData, CropStatus cropStatus, WeatherData weatherData) {
        decoratedMachine.update(soilData, cropStatus, weatherData);
    }
}

class LoggingDecorator extends FarmMachineDecorator {
    public LoggingDecorator(FarmMachine decoratedMachine) {
        super(decoratedMachine);
    }

    @Override
    public void startWork() {
        System.out.printf("[日志] 设备 %s(%s) 开始作业\n", getId(), getType());
        super.startWork();
    }

    @Override
    public void stopWork() {
        System.out.printf("[日志] 设备 %s(%s) 停止作业\n", getId(), getType());
        super.stopWork();
    }
}

// --------------------- 核心功能模块 ---------------------
// 农机设备接口
interface FarmMachine extends EnvironmentObserver {
    String getId();
    String getType();
    double getFuelLevel();
    Position getPosition();
    MachineState getState();
    void startWork();
    void stopWork();
}

// 具体农机实现
class Seeder implements FarmMachine {
    private static int counter = 0;
    private final String id = "S" + (++counter);
    private double fuelLevel = 100.0;
    private Position position = new Position(0, 0);
    private MachineState state = new IdleState();

    @Override
    public String getId() {
        return id;
    }

    @Override
    public String getType() {
        return "播种机";
    }

    @Override
    public double getFuelLevel() {
        return fuelLevel;
    }

    @Override
    public Position getPosition() {
        return position;
    }

    @Override
    public MachineState getState() {
        return state;
    }

    @Override
    public void startWork() {
        this.state = new WorkingState();
        this.state.handle(this);
    }

    @Override
    public void stopWork() {
        this.state = new IdleState();
        this.state.handle(this);
    }

    @Override
    public void update(SoilData soilData, CropStatus cropStatus, WeatherData weatherData) {
        System.out.printf("[%s] 环境数据更新 - 土壤: %s, 作物: %s, 天气: %s\n",
                getType(), soilData, cropStatus, weatherData);

        if (soilData.getHumidity() > 80) {
            System.out.printf("[%s] 检测到湿度过高(%.2f%%)，调整播种策略\n",
                    getType(), soilData.getHumidity());
        }
    }
}

class Sprayer implements FarmMachine {
    private static int counter = 0;
    private final String id = "P" + (++counter);
    private double fuelLevel = 100.0;
    private Position position = new Position(0, 0);
    private MachineState state = new IdleState();

    @Override
    public String getId() {
        return id;
    }

    @Override
    public String getType() {
        return "喷药机";
    }

    @Override
    public double getFuelLevel() {
        return fuelLevel;
    }

    @Override
    public Position getPosition() {
        return position;
    }

    @Override
    public MachineState getState() {
        return state;
    }

    @Override
    public void startWork() {
        this.state = new WorkingState();
        this.state.handle(this);
    }

    @Override
    public void stopWork() {
        this.state = new IdleState();
        this.state.handle(this);
    }

    @Override
    public void update(SoilData soilData, CropStatus cropStatus, WeatherData weatherData) {
        System.out.printf("[%s] 环境数据更新 - 土壤: %s, 作物: %s, 天气: %s\n",
                getType(), soilData, cropStatus, weatherData);

        if (cropStatus.getHealthIndex() < 0.7) {
            System.out.printf("[%s] 检测到作物健康指数低(%.2f)，准备喷药\n",
                    getType(), cropStatus.getHealthIndex());
        }
    }
}

class Harvester implements FarmMachine {
    private static int counter = 0;
    private final String id = "H" + (++counter);
    private double fuelLevel = 100.0;
    private Position position = new Position(0, 0);
    private MachineState state = new IdleState();

    @Override
    public String getId() {
        return id;
    }

    @Override
    public String getType() {
        return "收割机";
    }

    @Override
    public double getFuelLevel() {
        return fuelLevel;
    }

    @Override
    public Position getPosition() {
        return position;
    }

    @Override
    public MachineState getState() {
        return state;
    }

    @Override
    public void startWork() {
        this.state = new WorkingState();
        this.state.handle(this);
    }

    @Override
    public void stopWork() {
        this.state = new IdleState();
        this.state.handle(this);
    }

    @Override
    public void update(SoilData soilData, CropStatus cropStatus, WeatherData weatherData) {
        System.out.printf("[%s] 环境数据更新 - 土壤: %s, 作物: %s, 天气: %s\n",
                getType(), soilData, cropStatus, weatherData);

        if ("成熟期".equals(cropStatus.getGrowthStage())) {
            System.out.printf("[%s] 检测到作物成熟，准备收割\n", getType());
        }
    }
}

// 农机管理类 - 修改构造函数，添加环境监测器参数
class FarmMachineManager {
    private final Map<String, FarmMachine> machines = new HashMap<>();
    private final FarmMachineFactory factory = new ConcreteFarmMachineFactory();
    private final EnvironmentMonitor environmentMonitor;

    // 修改构造函数，接收环境监测器
    public FarmMachineManager(EnvironmentMonitor environmentMonitor) {
        this.environmentMonitor = environmentMonitor;
    }

    public void addMachine(String type) {
        FarmMachine machine = factory.createMachine(type);
        machines.put(machine.getId(), machine);
        // 注册为环境观察者
        environmentMonitor.addObserver(machine);
        System.out.printf("添加设备: %s(%s)\n", machine.getType(), machine.getId());
    }

    public void removeMachine(String id) {
        FarmMachine machine = machines.remove(id);
        if (machine != null) {
            // 从观察者列表中移除
            environmentMonitor.removeObserver(machine);
            System.out.printf("移除设备: %s(%s)\n", machine.getType(), machine.getId());
        } else {
            System.out.printf("设备不存在: ID=%s\n", id);
        }
    }

    public void listMachines() {
        System.out.println("\n当前设备列表:");
        for (FarmMachine machine : machines.values()) {
            System.out.printf("- %s(%s) - 位置: %s, 油量: %.2f%%, 状态: %s\n",
                    machine.getType(),
                    machine.getId(),
                    machine.getPosition(),
                    machine.getFuelLevel(),
                    machine.getState().getClass().getSimpleName().replace("State", ""));
        }
    }

    public FarmMachine getMachine(String id) {
        return machines.get(id);
    }
}

// 路径规划器
class PathPlanner {
    private final Map<String, PathPlanningStrategy> strategies = new HashMap<>();

    public PathPlanner() {
        strategies.put("normal", new NormalPathStrategy());
        strategies.put("wet", new WetSoilPathStrategy());
    }

    public void planPath(String machineId, Map<Position, SoilData> soilData, List<Position> obstacles) {
        System.out.printf("为设备 %s 规划路径...\n", machineId);

        // 根据土壤数据选择策略
        boolean hasWetArea = false;
        for (SoilData data : soilData.values()) {
            if (data.getHumidity() > 80) {
                hasWetArea = true;
                break;
            }
        }

        PathPlanningStrategy strategy = hasWetArea ?
                strategies.get("wet") : strategies.get("normal");

        List<Position> path = strategy.calculatePath(soilData, obstacles);
        System.out.printf("路径规划完成，共 %d 个路径点\n", path.size());
    }
}

// 安全事件类
class SafetyEvent {
    enum Type { OBSTACLE, WEATHER, FAULT }

    private final Type type;
    private final String description;
    private boolean resolved = false;

    public SafetyEvent(Type type, String description) {
        this.type = type;
        this.description = description;
    }

    // Getter & Setter
    public Type getType() { return type; }
    public String getDescription() { return description; }
    public boolean isResolved() { return resolved; }
    public void setResolved(boolean resolved) { this.resolved = resolved; }
}

// 用户类（用于代理模式）
class User {
    private final String username;
    private final Set<String> permissions;

    public User(String username, Set<String> permissions) {
        this.username = username;
        this.permissions = permissions;
    }

    public boolean hasPermission(String permission) {
        return permissions.contains(permission);
    }

    public String getUsername() {
        return username;
    }

    // 修复getPermissions方法
    public String getPermissions() {
        return String.join(", ", permissions);
    }
}

// --------------------- 人机交互界面 ---------------------
class ConsoleUI {
    private final FarmSystemFacade facade;
    private final Scanner scanner = new Scanner(System.in);
    private User currentUser;

    public ConsoleUI() {
        this.facade = new FarmSystemFacade();
        login();
    }

    private void login() {
        System.out.println("==== 智能农机管理系统 ====");
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();

        // 模拟用户权限（实际应用中应从数据库获取）
        if ("admin".equals(username)) {
            currentUser = new User(username,
                    new HashSet<>(Arrays.asList("ADD_MACHINE", "REMOVE_MACHINE", "START_WORK", "STOP_WORK")));
        } else {
            currentUser = new User(username,
                    new HashSet<>(Arrays.asList("START_WORK", "STOP_WORK")));
        }

        System.out.printf("欢迎，%s！您拥有以下权限: %s\n",
                username, currentUser.getPermissions());
    }

    public void run() {
        while (true) {
            printMainMenu();
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消耗换行符

            switch (choice) {
                case 1:
                    manageMachines();
                    break;
                case 2:
                    monitorEnvironment();
                    break;
                case 3:
                    planPaths();
                    break;
                case 4:
                    manageTasks();
                    break;
                case 5:
                    handleSafetyEvents();
                    break;
                case 0:
                    System.out.println("退出系统...");
                    return;
                default:
                    System.out.println("无效选择，请重新输入");
            }
        }
    }

    private void printMainMenu() {
        System.out.println("\n==== 主菜单 ====");
        System.out.println("1. 农机设备管理");
        System.out.println("2. 农田环境监测");
        System.out.println("3. 智能路径规划");
        System.out.println("4. 任务执行与控制");
        System.out.println("5. 安全事件处理");
        System.out.println("0. 退出系统");
        System.out.print("请选择操作: ");
    }

    private void manageMachines() {
        while (true) {
            System.out.println("\n==== 农机设备管理 ====");
            System.out.println("1. 添加设备");
            System.out.println("2. 移除设备");
            System.out.println("3. 查看设备列表");
            System.out.println("0. 返回主菜单");
            System.out.print("请选择操作: ");

            int choice = scanner.nextInt();
            scanner.nextLine(); // 消耗换行符

            switch (choice) {
                case 1:
                    if (!currentUser.hasPermission("ADD_MACHINE")) {
                        System.out.println("权限不足");
                        break;
                    }
                    System.out.print("请输入设备类型(播种机/喷药机/收割机): ");
                    String type = scanner.nextLine();
                    facade.addMachine(type);
                    break;
                case 2:
                    if (!currentUser.hasPermission("REMOVE_MACHINE")) {
                        System.out.println("权限不足");
                        break;
                    }
                    System.out.print("请输入设备ID: ");
                    String id = scanner.nextLine();
                    facade.removeMachine(id);
                    break;
                case 3:
                    facade.listMachines();
                    break;
                case 0:
                    return;
                default:
                    System.out.println("无效选择，请重新输入");
            }
        }
    }

    private void monitorEnvironment() {
        System.out.println("\n==== 农田环境监测 ====");
        System.out.print("请输入土壤湿度(%): ");
        double soilHumidity = scanner.nextDouble();
        System.out.print("请输入土壤pH值: ");
        double soilPh = scanner.nextDouble();
        System.out.print("请输入土壤养分含量: ");
        double soilNutrient = scanner.nextDouble();
        scanner.nextLine(); // 消耗换行符

        System.out.print("请输入作物生长阶段: ");
        String growthStage = scanner.nextLine();
        System.out.print("请输入作物健康指数: ");
        double healthIndex = scanner.nextDouble();
        scanner.nextLine(); // 消耗换行符

        System.out.print("请输入气温(℃): ");
        double temperature = scanner.nextDouble();
        System.out.print("请输入空气湿度(%): ");
        double airHumidity = scanner.nextDouble();
        System.out.print("请输入风速(m/s): ");
        double windSpeed = scanner.nextDouble();
        scanner.nextLine(); // 消耗换行符

        SoilData soilData = new SoilData(soilHumidity, soilPh, soilNutrient);
        CropStatus cropStatus = new CropStatus(growthStage, healthIndex);
        WeatherData weatherData = new WeatherData(temperature, airHumidity, windSpeed);

        facade.updateEnvironmentData(soilData, cropStatus, weatherData);
    }

    private void planPaths() {
        System.out.println("\n==== 智能路径规划 ====");
        System.out.print("请输入设备ID: ");
        String machineId = scanner.nextLine();

        // 模拟土壤数据和障碍物
        Map<Position, SoilData> soilData = new HashMap<>();
        soilData.put(new Position(10, 10), new SoilData(75, 6.5, 0.8));
        soilData.put(new Position(20, 20), new SoilData(85, 6.8, 0.9)); // 湿地区域

        List<Position> obstacles = new ArrayList<>();
        obstacles.add(new Position(15, 15));

        facade.planPath(machineId, soilData, obstacles);
    }

    private void manageTasks() {
        while (true) {
            System.out.println("\n==== 任务执行与控制 ====");
            System.out.println("1. 启动设备");
            System.out.println("2. 停止设备");
            System.out.println("0. 返回主菜单");
            System.out.print("请选择操作: ");

            int choice = scanner.nextInt();
            scanner.nextLine(); // 消耗换行符

            switch (choice) {
                case 1:
                    System.out.print("请输入设备ID: ");
                    String startId = scanner.nextLine();
                    FarmMachine startMachine = getMachineWithProxy(startId);
                    if (startMachine != null) {
                        facade.executeCommand(new StartWorkCommand(startMachine));
                    }
                    break;
                case 2:
                    System.out.print("请输入设备ID: ");
                    String stopId = scanner.nextLine();
                    FarmMachine stopMachine = getMachineWithProxy(stopId);
                    if (stopMachine != null) {
                        facade.executeCommand(new StopWorkCommand(stopMachine));
                    }
                    break;
                case 0:
                    return;
                default:
                    System.out.println("无效选择，请重新输入");
            }
        }
    }

    private void handleSafetyEvents() {
        System.out.println("\n==== 安全事件处理 ====");
        System.out.println("1. 障碍物检测");
        System.out.println("2. 恶劣天气");
        System.out.println("3. 设备故障");
        System.out.print("请选择事件类型: ");

        int choice = scanner.nextInt();
        scanner.nextLine(); // 消耗换行符

        SafetyEvent.Type type;
        String description;

        switch (choice) {
            case 1:
                type = SafetyEvent.Type.OBSTACLE;
                System.out.print("请输入障碍物位置: ");
                description = scanner.nextLine();
                break;
            case 2:
                type = SafetyEvent.Type.WEATHER;
                System.out.print("请输入天气描述: ");
                description = scanner.nextLine();
                break;
            case 3:
                type = SafetyEvent.Type.FAULT;
                System.out.print("请输入故障描述: ");
                description = scanner.nextLine();
                break;
            default:
                System.out.println("无效选择");
                return;
        }

        SafetyEvent event = new SafetyEvent(type, description);
        facade.handleSafetyEvent(event);
    }

    private FarmMachine getMachineWithProxy(String id) {
        FarmMachine machine = facade.getMachine(id);
        if (machine == null) {
            System.out.printf("设备不存在: ID=%s\n", id);
            return null;
        }

        // 添加代理和装饰器
        FarmMachine proxy = new FarmMachineProxy(machine, currentUser);
        return new LoggingDecorator(proxy);
    }
}

// --------------------- 系统入口 ---------------------
// 类名改为Main，符合Java标准
public class Main {
    public static void main(String[] args) {
        ConsoleUI ui = new ConsoleUI();
        ui.run();
    }
}